<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="">
        <table>
            <caption><h2>注册</h2></caption>
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="username"></td>
            </tr>
            <tr>
                <td>密码</td>
                <td>
                    <input type="password" name="password" id="">
                </td>
            </tr>
            <tr>
                <td>确认密码</td>
                <td>
                    <input type="password" name="repass">
                </td>
            </tr>
            <tr>
                <td>用户昵称</td>
                <td>
                    <input type="text" name="nickname" id="">
                </td>
            </tr>
            <tr>
                <td>
                    <input type="submit">
                </td>
            </tr>
        </table>
    </form>
</body>
<script>
    var form = document.querySelector('form')
    var username = document.querySelector('[name = "username"]')
    var password = document.querySelector('[name = "password"]')
    var repass = document.querySelector('[name = "repass"]')
    var nickname = document.querySelector('[name = "nickname"]')
    form.addEventListener('submit',onsubmit)

    function onsubmit(){
        //阻止默认行为
        window.event.returnValue = false
        //验证账号
        var usernameReg = /^[a-z0-9]\w{4,11}$/
        if(!usernameReg.test(username.value)){
            alert('账号错误')
            return false
        }
        //验证密码
        var passwordReg = /\w{6,12}/
        if(!passwordReg.test(password.value)){
            alert('密码错误')
            return false
        }
        if(repass.value != password.value){
            alert('两次密码输入不一致')
            return false
        }
        if(nickname.value.trim() === ''){
            alert('名字不能为空')
        }
        //ajax请求
        var xhr = new XMLHttpRequest;
        xhr.open('post','http://localhost:8888/users/register');
        xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')
        xhr.send(`username=${username.value}&password=${password.value}&rpassword=${repass.value}&nickname=${nickname.value}`)
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                if(xhr.status>=200 && xhr.status<300){
                    var res = xhr.responseText;
                    res = JSON.parse(res)
                    // console.log(res);
                    var {code,message} = res
                    if(code === 1){
                        alert(message)
                        location.href = './login.html'
                    }else{
                        alert(message)
                    }
                }
            }
        }
    }
</script>
</html>